#!/bin/sh
#
# Copyright (C) 2019  Etersoft
# Copyright (C) 2019  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# remove duplicates
try_fix_apt_rpm_dupls()
{
    info "Check for duplicates (internal implementation) ..."
    local TESTPKG="ignoreflock"
    local has_testpkg=""
    if epm --quiet installed $TESTPKG ; then
        has_testpkg=1
        sudocmd epm remove --auto $TESTPKG || return
    fi
    local PKGLIST
    PKGLIST=$(LC_ALL=C sudorun apt-get install $TESTPKG 2>&1 | grep "W: There are multiple versions of" | \
        sed -e 's|W: There are multiple versions of "\(.*\)" in your system.|\1|')
    local TODEL
    for i in $PKGLIST ; do
        local pkg=${i/.32bit/}
        local todel="$(rpm -q $pkg | head -n1)"
        local todel2="$(rpm -q $pkg | head -n2 | tail -n1)"
        if [ "$todel" = "$todel2" ] ; then
            echo "Fix the same name duplicates for $pkg..."
            sudocmd rpm -e "$todel" --allmatches --nodeps --justdb && epm install $pkg && continue
        fi
                # first use older package
                [ "$(rpmevrcmp "$todel" "$todel2")" = "1" ] && todel="$todel2"
        sudocmd rpm -e "$todel" || TODEL="$TODEL $todel"
    done
    [ -n "$TODEL" ] && sudocmd rpm -e $TODEL
    [ -n "$has_testpkg" ] && epm install $TESTPKG
}

epm_dedup()
{
case "$BASEDISTRNAME" in
    "alt")
        assure_exists /usr/share/apt/scripts/dedup.lua apt-scripts
        if [ -z "$direct" ] && [ -f /usr/share/apt/scripts/dedup.lua ] ; then
            info "Check for duplicates via apt-get dedup from apt-scripts (also you can use internal EPM dedup implementation with --direct option)"
            sudocmd apt-get dedup
        else
            info "You can use dedup from apt-scripts package"
            try_fix_apt_rpm_dupls
        fi
        ;;
    *)
        fatal "Have no suitable command for $PMTYPE"
        ;;
esac

}
